package com.rjwh.dingdong.client.fragment.menu;

import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aishua.lib.utils.AsStrUtils;
import com.bumptech.glide.Glide;
import com.orangegangsters.github.swipyrefreshlayout.library.SwipyRefreshLayout;
import com.orangegangsters.github.swipyrefreshlayout.library.SwipyRefreshLayoutDirection;
import com.rjwh.dingdong.client.R;
import com.rjwh.dingdong.client.activity.radio.RadioLocalPlayListActivity;
import com.rjwh.dingdong.client.adapter.RadioAlbumListAdapter;
import com.rjwh.dingdong.client.adapter.RadioPageMenuGridAdapter;
import com.rjwh.dingdong.client.adapter.RadioPageModuleListAdapter;
import com.rjwh.dingdong.client.bean.localbean.RadioPageAlbumData;
import com.rjwh.dingdong.client.bean.localbean.RadioPageBannerData;
import com.rjwh.dingdong.client.bean.localbean.RadioPageMenuData;
import com.rjwh.dingdong.client.bean.localbean.RadioPageModuleData;
import com.rjwh.dingdong.client.fragment.BaseFragment;
import com.rjwh.dingdong.client.mvp.presenter.impl.RadioPagePresenter;
import com.rjwh.dingdong.client.mvp.view.RadioPageView;
import com.rjwh.dingdong.client.player.IPlayback;
import com.rjwh.dingdong.client.player.PlayConstants;
import com.rjwh.dingdong.client.player.PlayState;
import com.rjwh.dingdong.client.service.PlaybackService;
import com.rjwh.dingdong.client.util.LogUtil;
import com.rjwh.dingdong.client.util.RxBus;
import com.rjwh.dingdong.client.util.UrlUtil;
import com.rjwh.dingdong.client.view.IndicatorHackyViewPager;
import com.rjwh.dingdong.client.view.NoScrollListView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Observable;
import rx.Subscriber;

/**
 * @author Kay
 * @ClassName RadioPageFragment
 * @Description
 * @date 2016-10-25
 * @history 2016-10-25 author: description:
 */

public class RadioPageFragment extends BaseFragment implements AdapterView.OnItemClickListener, RadioPageView {

    @BindView(R.id.radio_page_title_right_img)
    ImageView radioTitleRightImg;
    @BindView(R.id.loading_layout)
    RelativeLayout loadingLayout;
    @BindView(R.id.error_layout)
    RelativeLayout errorLayout;
    @BindView(R.id.radio_page_recommended_album_list)
    NoScrollListView radioRecommendedAlbumList;
    @BindView(R.id.radio_page_mPullRefreshView)
    SwipyRefreshLayout radioMPullRefreshView;
    @BindView(R.id.radio_page_module_list)
    NoScrollListView radioPageModuleList;
    @BindView(R.id.radio_page_banner_viewpager)
    IndicatorHackyViewPager radioPageBannerViewpager;
    @BindView(R.id.radio_page_tab_recommended_album_text)
    TextView radioPageTabRecommendedAlbumText;
    @BindView(R.id.radio_page_menu_gv)
    GridView radioPageMenuGv;
    @BindView(R.id.radio_page_tab_recommended_album_more_arrow)
    TextView radioPageTabRecommendedAlbumMoreArrow;

    private IPlayback mPlayer;
    private Observable<PlayState> observablePlayState;

    private RadioAlbumListAdapter recommendedAlbumListAdapter;
    private RadioPagePresenter presenter;
    private RadioPageModuleListAdapter moduleListAdapter;
    private List<RadioPageBannerData> bannerlist;
    private RadioPageMenuGridAdapter radioPageMenuGridAdapter;
    private MyPagerAdapter viewPagerAdapter;
    private TimeCount time;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.radio_page_layout, container, false);
        ButterKnife.bind(this, rootView);
        initView();
        return rootView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        init();
        doGetRadioPage();
    }

    public void init() {
        presenter = new RadioPagePresenter(getContext(), this);
        presenter.subscribe();
        observablePlayState = RxBus.get().register(PlayConstants.ACTION_PLAY_STATUS_CHANGED, PlayState.class);
        addSubscription(observablePlayState, subscriberPlayState);
    }

    private void initView() {
        radioPageModuleList.setFocusable(false);
        radioRecommendedAlbumList.setFocusable(false);

        moduleListAdapter = new RadioPageModuleListAdapter(getContext());
        radioPageModuleList.setAdapter(moduleListAdapter);

        radioPageMenuGridAdapter = new RadioPageMenuGridAdapter(getContext());
        radioPageMenuGv.setAdapter(radioPageMenuGridAdapter);
        recommendedAlbumListAdapter = new RadioAlbumListAdapter(getContext(), true);
        radioRecommendedAlbumList.setAdapter(recommendedAlbumListAdapter);

        radioMPullRefreshView.setOnRefreshListener(new SwipyRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh(SwipyRefreshLayoutDirection direction) {
                if (direction == SwipyRefreshLayoutDirection.TOP) {
                    presenter.doGetRadioPage();
                }
            }
        });

        radioRecommendedAlbumList.setOnItemClickListener(this);
        radioPageMenuGv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                RadioPageMenuGridAdapter adapter = (RadioPageMenuGridAdapter) parent.getAdapter();
                RadioPageMenuData item = adapter.getItem(position);
                String actionurl = item.getActionurl();
                if (!AsStrUtils.isEmpty(actionurl)) {
                    UrlUtil.handelUrl(getContext(), actionurl, true);
                }
            }
        });
        viewPagerAdapter = new MyPagerAdapter();
        radioPageBannerViewpager.setAdapter(viewPagerAdapter);
        radioPageBannerViewpager.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                    case MotionEvent.ACTION_MOVE:
                        cancelTimer();
                        break;
                    case MotionEvent.ACTION_UP:
                    case MotionEvent.ACTION_CANCEL:
                        if (viewPagerAdapter.getCount() > 2) {
                            startTimer();
                        }
                        break;

                    default:
                        break;
                }
                return false;
            }
        });
    }

    private void updataBannerView() {
        if (time == null) {
            time = new TimeCount(5 * 1000, 1000);// 构造CountDownTimer对象
        }
        viewPagerAdapter.addList(bannerlist);
        startTimer();

    }

    class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);// 参数依次为总时长,和计时的时间间隔
        }

        @Override
        public void onFinish() {// 计时完毕时触发
            if (viewPagerAdapter == null) {
                return;
            }
            int count = viewPagerAdapter.getCount();
            if (count > 2) { // 多于2个，才循环
                int index = radioPageBannerViewpager.getCurrentItem();
                index = (index + 1) % count;
                radioPageBannerViewpager.setCurrentItem(index, true);
                time.start();
            } else {
                time.cancel();
            }
        }

        @Override
        public void onTick(long millisUntilFinished) {// 计时过程显示
        }
    }


    @OnClick({R.id.radio_page_title_right_img, R.id.btn_refresh})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.radio_page_title_right_img:
                //TODO 右上角按钮
                RadioLocalPlayListActivity.startActivity(getContext());
                break;
            case R.id.btn_refresh:
                doGetRadioPage();
                break;
        }
    }

    public class MyPagerAdapter extends PagerAdapter {

        private List<RadioPageBannerData> bannerlist = new ArrayList<>();

        public void addList(List<RadioPageBannerData> list) {
            if (list != null) {
                bannerlist.clear();
                bannerlist.addAll(list);
                notifyDataSetChanged();
            }
        }

        @Override
        public Object instantiateItem(ViewGroup container, final int position) {
            ImageView imageView = new ImageView(getContext());
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            if (bannerlist.get(position).getBannerurl() != null) {
                Glide.with(getContext()).load(bannerlist.get(position).getBannerurl()).placeholder(R.drawable.icon_pic_holder).error(R.drawable.icon_pic_holder).dontAnimate().into(imageView);
            }
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (bannerlist.get(position).getBannerid() != null && bannerlist.get(position).getActionurl() != null) {
                        UrlUtil.handelUrl(getContext(), bannerlist.get(position).getActionurl(), true);
                    }
                }
            });
            container.addView(imageView);
            return imageView;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }

        @Override
        public int getCount() {
            return bannerlist.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }
    }

    private void doGetRadioPage() {
        hideErrorView();
        showLoadingView();
        presenter.doGetRadioPage();
    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        RadioAlbumListAdapter adapter = (RadioAlbumListAdapter) parent.getAdapter();
        RadioPageAlbumData item = adapter.getItem(position);
        String actionurl = item.getActionurl();
        if (!AsStrUtils.isEmpty(actionurl)) {
            UrlUtil.handelUrl(getContext(), actionurl, true);
        }
    }

    @Override
    public void showLoadingView() {
        if (loadingLayout != null) {
            loadingLayout.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void hideLoadingView() {
        if (loadingLayout != null) {
            loadingLayout.setVisibility(View.GONE);
        }
    }

    @Override
    public void showErrorView() {
        if (errorLayout != null) {
            errorLayout.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void hideErrorView() {
        if (errorLayout != null) {
            errorLayout.setVisibility(View.GONE);
        }
    }

    @Override
    public void LoadData(List<RadioPageBannerData> bannerlist, List<RadioPageMenuData> menulist, List<RadioPageModuleData> modulelist, List<RadioPageAlbumData> recommendlist, String modulename, String actionurl) {
        this.bannerlist = bannerlist;
        updataBannerView();
        moduleListAdapter.clearAll();
        moduleListAdapter.appendToList(modulelist);

        radioPageMenuGridAdapter.clearAll();
        radioPageMenuGridAdapter.appendToList(menulist);

        recommendedAlbumListAdapter.clearAll();
        recommendedAlbumListAdapter.appendToList(recommendlist);

        if (!AsStrUtils.isEmpty(modulename)) {
            radioPageTabRecommendedAlbumText.setText(modulename);
        }
        if (!AsStrUtils.isEmpty(actionurl)) {
            radioPageTabRecommendedAlbumMoreArrow.setVisibility(View.VISIBLE);
            UrlUtil.handelUrl(getContext(), actionurl, true);
        } else {
            radioPageTabRecommendedAlbumMoreArrow.setVisibility(View.GONE);
        }
    }

    @Override
    public void setRefreshing(boolean isRefresh) {
        radioMPullRefreshView.setRefreshing(isRefresh);
    }

    @Override
    public void onPlaybackServiceBound(PlaybackService service) {
        this.mPlayer = service;
    }

    @Override
    public void onPlaybackServiceUnbound() {
        this.mPlayer = null;
    }

    @Override
    public void updatePlayToggle(PlayState play) {
        if (play == PlayState.PLAY) {
            startPlayAnimation(true);
        } else {
            startPlayAnimation(false);
        }
    }

    public void startPlayAnimation(boolean flag) {
        radioTitleRightImg.setImageResource(R.drawable.music_playing);
        AnimationDrawable animaDrawable = (AnimationDrawable) radioTitleRightImg.getDrawable();
        //启动动画
        if (flag) {
            LogUtil.e("HTML", "animation - start");
            animaDrawable.start();
        } else {
            //停止
            LogUtil.e("HTML", "animation - stop");
            animaDrawable.stop();
            radioTitleRightImg.setImageResource(R.drawable.icon_radio_title_img);
        }
//        radioTitleRightImg.startAnimation();
    }

    @Override
    public void onResume() {
        super.onResume();
        startTimer();
    }

    @Override
    public void onPause() {
        super.onPause();
        cancelTimer();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        LogUtil.d("MainPageFragment", "onHiddenChanged hidden: " + hidden);
        if (hidden) {
            cancelTimer();
        } else {
            startTimer();
        }
    }

    private void startTimer() {
        if (time != null) {
            time.start();
        }
    }

    private void cancelTimer() {
        if (time != null) {
            time.cancel();
        }
    }

    @Override
    public void onDestroy() {
        LogUtil.d("RaduiPage onDestroy");
        RxBus.get().unregister(PlayConstants.ACTION_PLAY_STATUS_CHANGED, observablePlayState);
        presenter.detachView();
        cancelTimer();
        time = null;
        super.onDestroy();
    }

    Subscriber subscriberPlayState = new Subscriber<PlayState>() {
        @Override
        public void onCompleted() {

        }

        @Override
        public void onError(Throwable e) {

        }


        @Override
        public void onNext(PlayState change) {
            LogUtil.d("RadioPageFragment", "change:" + change);
            updatePlayToggle(change);
        }
    };
}
